//Lissajous曲线. x = sin(m*t) y = cos(n*t)

class Lissajous{
    private cv:any;
    private cv2:any;
    private ctx:any;
    private ctx2:any;
    private RATIO: number = Math.PI / 10800;
    private m:number = 13 * this.RATIO;
    private n:number = 18 * this.RATIO;
    private t:number = 0;
    private ms:number = 10;
    private W:number;
    private H:number;
    private timer:any;
    constructor(cv,cv2){
        this.cv = cv;
        this.cv2 = cv2;
        cv2.width = this.cv.width;
        cv2.height = this.cv.height;
        
        this.ctx = cv.getContext('2d');
        this.ctx2 = cv2.getContext('2d');
        this.W = this.cv.width - 20;    //处理边缘
        this.H = this.cv.height - 20;   //处理边缘
        this.timer = null;
    }

    initRatio(m,n){
        clearInterval(this.timer);
        this.ctx.restore();
        this.ctx2.restore();

        this.ctx.clearRect(0, 0, this.W + 20, this.H + 20);
        this.ctx2.clearRect(0, 0, this.W + 20, this.H + 20);
        this.t = 0;
        this.m = m * this.RATIO;
        this.n = n * this.RATIO;
        this.draw();
    }
    
    step(){
        //绘制新的路径
        

        let x = Math.floor(this.W / 2 * Math.sin(this.m * this.t)),
            y = Math.floor(this.H / 2 * Math.sin(this.n * this.t));
        this.ctx.lineTo(x,y);
        this.ctx.closePath();
        this.ctx.stroke();
        this.ctx.beginPath();
        this.ctx.moveTo(x,y);

        //清楚上一个圆
        this.ctx2.clearRect(-this.W/2 - 10,-this.H/2 - 10, this.W + 20, this.H + 20)
        //绘制新的圆
        this.ctx2.beginPath();
        this.ctx2.arc(x,y,7,0,Math.PI*2);
        this.ctx2.closePath();
        this.ctx2.fill();
    }

    draw(){
        this.ctx.save();
        this.ctx2.save();
        this.ctx.strokeStyle= "rgba(210,33,33,0.5)";
        this.ctx.lineWidth = 3;
        this.ctx2.fillStyle = "rgba(32,140,210,0.9)";

        this.ctx.translate(this.W/2 + 10,this.H/2 + 10);
        this.ctx2.translate(this.W/2 + 10,this.H/2 + 10);

        this.ctx.beginPath();
        this.ctx.moveTo(0,0);
        this.timer = setInterval(()=>{
            this.t += 10;
            this.step();
        },this.ms);
    }
}